/**
 * Created by Administrator on 2016/9/18.
 */

define(function (require, exports) {
    var ajaxUtil = require('util/ajaxUtil').ajaxUtil;
    var logUtil = require('util/logUtil').logUtil;
    var commonUtil = require('util/commonUtil').commonUtil;

    function init() {
        bindEvent();
        initTemplateCategoryTreeList();
    }

    var urls = {};
    urls.app_template_category_query = '/admin/category/template-category-query';
    urls.app_template_category_save = '/admin/category/template-category-save';
    urls.app_template_category_delete = '/admin/category/template-category-del';

    var controls = {};
    controls.app_template_category_list_panel = $('#app_template_category_list_panel');
    controls.app_template_category_detail_image_upload = $('#app_template_category_detail_image_upload');
    controls.app_template_category_detail_image_upload_selected = $('#app_template_category_detail_image_upload_selected');

    var G_ADD_ARGS = null;
    var G_ADD_RREE_NODE = null;

    var G_ADD_IMAGE = null;
    var G_ADD_IMAGE_SELECTED = null;

    var G_MODIFY_ID = null;
    var G_MODIFY_STATUS = false;

    var setting = {
        async: {
            enable: true,
            url: urls.app_template_category_query,
            autoParam: ["id"],
            dataFilter: filter,
            type: "get"
        },
        view: {
            expandSpeed: "",
            addHoverDom: addHoverDom,
            removeHoverDom: removeHoverDom,
            selectedMulti: false
        },
        edit: {
            enable: true,
            drag: false,
            showRenameBtn: false,
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            beforeRemove: beforeRemove,
            // beforeRename: beforeRename,
        }
    };

    function filter(treeId, parentNode, ret) {
        if (ret.status != 0) return null;

        var nodes = ret.data;
        for (var i = 0; i < nodes.length; i++) {
            nodes[i].isParent = true;
            nodes[i].name = nodes[i].val;
        }

        return nodes;
    }

    function initTemplateCategoryTreeList() {
        ajaxUtil.doAjaxGet(urls.app_template_category_query, {id: '0'}).done(function (ret) {
            if (ret.status != 0) {
                commonUtil.toast('初始化列表失败');
                return;
            }

            var nodes = ret.data;

            for (var i = 0; i < nodes.length; i++) {
                nodes[i].isParent = true;
                nodes[i].name = nodes[i].val;
            }

            $.fn.zTree.init($("#app_template_category_menu_tree"), setting, nodes);
        });
    }

    function beforeRemove(treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj("app_template_category_menu_tree");
        zTree.selectNode(treeNode);

        ajaxUtil.doAjaxGet(urls.app_template_category_delete, {'id': treeNode.id}).done(function (ret) {
            commonUtil.toast(ret.msg);
        });
    }

    function addHoverDom(treeId, treeNode) {
        var sObj = $("#" + treeNode.tId + "_span");

        if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
        if (treeNode.editNameFlag || $("#editBtn_" + treeNode.tId).length > 0) return;


        var editStr = "<span class='button edit' id='editBtn_" + treeNode.tId + "' title='rename' onfocus='this.blur();'></span>";
        sObj.after(editStr);
        var btnEdit = $("#editBtn_" + treeNode.tId);
        if (btnEdit) btnEdit.bind("click", function () {
            $('#app_template_category_detail_list_panel').modal('show');
            $('#app_template_category_detail_list_panel').find('input[type=text]').val('')
            $('#app_template_category_detail_list_panel').find('img:eq(0)').attr('src', '')
            $('#app_template_category_detail_list_panel').find('img:eq(1)').attr('src', '')
            G_ADD_IMAGE = null;
            G_ADD_IMAGE_SELECTED = null;

            G_ADD_ARGS = {};

            G_MODIFY_ID = treeNode.id;
            G_MODIFY_STATUS = true;

            console.log(treeNode);

            $('#app_template_category_detail_list_panel').find('input[type=text]').val(treeNode.name)
            $('#app_template_category_detail_list_panel').find('img:eq(0)').attr('src', treeNode.img_url || "")
            $('#app_template_category_detail_list_panel').find('img:eq(1)').attr('src', treeNode.img_selected_url || "")

            if (treeNode.img_url) {
                G_ADD_IMAGE = treeNode.img_url;
            }

            if (treeNode.img_selected_url) {
                G_ADD_IMAGE_SELECTED = treeNode.img_selected_url;
            }

            G_ADD_RREE_NODE = treeNode;

            return false;
        });


        var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='add node' onfocus='this.blur();'></span>";
        sObj.after(addStr);
        var btn = $("#addBtn_" + treeNode.tId);
        if (btn) btn.bind("click", function () {
            if (treeNode.level + 1 >= 2) {
                commonUtil.toast('无效操作:模板分类最多为2级');
                return false;
            }


            $('#app_template_category_detail_list_panel').modal('show');
            $('#app_template_category_detail_list_panel').find('input[type=text]').val('')
            $('#app_template_category_detail_list_panel').find('img:eq(0)').attr('src', '')
            $('#app_template_category_detail_list_panel').find('img:eq(1)').attr('src', '')
            G_MODIFY_ID = null;
            G_MODIFY_STATUS = false;

            G_ADD_ARGS = {
                level: parseInt(treeNode.level + 1),
                pid: treeNode.id,
            };

            G_ADD_RREE_NODE = treeNode;

            return false;
        });
    }

    function removeHoverDom(treeId, treeNode) {
        $("#addBtn_" + treeNode.tId).unbind().remove();
        $("#editBtn_" + treeNode.tId).unbind().remove();
    }

    function bindEvent() {
        controls.app_template_category_list_panel.find('button:eq(0)').bind('click', function () {
            $('#app_template_category_detail_list_panel').modal('show');
            G_MODIFY_ID = null;
            G_MODIFY_STATUS = false;
            $('#app_template_category_detail_list_panel').find('input[type=text]').val('')
            $('#app_template_category_detail_list_panel').find('img:eq(0)').attr('src', '')
            $('#app_template_category_detail_list_panel').find('img:eq(1)').attr('src', '')
            G_ADD_ARGS = {
                pid: 0,
            };

            G_ADD_RREE_NODE = null;
        });

        $('#app_template_category_detail_list_panel').find('button:eq(-2)').bind('click', function () {
            var rootName = $.trim($('#app_template_category_detail_list_panel').find('input[type=text]').val());
            if (!rootName) return commonUtil.toast('分类名称不能为空');

            G_ADD_ARGS.val = rootName;

            if (G_ADD_IMAGE) {
                G_ADD_ARGS.img_url = G_ADD_IMAGE;
            }

            if (G_ADD_IMAGE_SELECTED) {
                G_ADD_ARGS.img_selected_url = G_ADD_IMAGE_SELECTED;
            }


            if (G_MODIFY_STATUS) {
                G_ADD_ARGS.id = G_MODIFY_ID;

                ajaxUtil.doAjaxPost(urls.app_template_category_save, G_ADD_ARGS).done(function (ret) {
                    commonUtil.toast(ret.msg);
                    $('#app_template_category_detail_list_panel').modal('hide');
                    if (ret.status == 0) {
                        var zTree = $.fn.zTree.getZTreeObj("app_template_category_menu_tree");

                        G_ADD_RREE_NODE.name = rootName;
                        if (G_ADD_IMAGE) {
                            G_ADD_RREE_NODE.img_url = G_ADD_IMAGE;
                        }
                        if (G_ADD_IMAGE_SELECTED) {
                            G_ADD_RREE_NODE.img_selected_url = G_ADD_IMAGE_SELECTED;
                        }

                        zTree.updateNode(G_ADD_RREE_NODE);
                    }
                })
            } else {
                ajaxUtil.doAjaxPost(urls.app_template_category_save, G_ADD_ARGS).done(function (ret) {
                    commonUtil.toast(ret.msg);
                    $('#app_template_category_detail_list_panel').modal('hide');
                    if (ret.status == 0) {
                        var zTree = $.fn.zTree.getZTreeObj("app_template_category_menu_tree");

                        let nodeData = {
                            id: ret.data.id,
                            pid: G_ADD_ARGS.pid,
                            name: rootName
                        };

                        if (G_ADD_IMAGE) {
                            nodeData.img_url = G_ADD_IMAGE;
                        }

                        if (G_ADD_IMAGE_SELECTED) {
                            nodeData.img_selected_url = G_ADD_IMAGE_SELECTED;
                        }

                        zTree.addNodes(G_ADD_RREE_NODE, nodeData);
                    }
                })
            }
        })

        controls.app_template_category_detail_image_upload.fileinput({
            language: 'zh', //设置语言
            uploadUrl: '/admin/file/upload-to-ali-oss', //上传的地址
            allowedFileExtensions: ['jpg', 'jpeg', 'png'],//接收的文件后缀
            showUpload: false, //是否显示上传按钮
            showCaption: false,//是否显示标题,
            showRemove: false,
            uploadAsync: true,
            maxFileCount: 10,
            fileActionSettings: {
                showRemove: false,
            },
            browseLabel: '点击上传预览图',
            browseClass: "btn btn-primary", //按钮样式
        }).on("filebatchselected", function (event, files) {
            controls.app_template_category_detail_image_upload.fileinput("upload");
        }).on("fileuploaded", function (event, data, previewId, index) {
            console.log(data);
            var ret = data.response;
            if (ret.status != 0) {
                return commonUtil.toast(ret.msg);
            }
            G_ADD_IMAGE = ret.data.url;

            $('#app_template_category_detail_list_panel').find('img:eq(0)').attr('src', G_ADD_IMAGE)
        });

        controls.app_template_category_detail_image_upload_selected.fileinput({
            language: 'zh', //设置语言
            uploadUrl: '/admin/file/upload-to-ali-oss', //上传的地址
            allowedFileExtensions: ['jpg', 'jpeg', 'png'],//接收的文件后缀
            showUpload: false, //是否显示上传按钮
            showCaption: false,//是否显示标题,
            showRemove: false,
            uploadAsync: true,
            maxFileCount: 10,
            fileActionSettings: {
                showRemove: false,
            },
            browseLabel: '点击上传预览图',
            browseClass: "btn btn-primary", //按钮样式
        }).on("filebatchselected", function (event, files) {
            controls.app_template_category_detail_image_upload_selected.fileinput("upload");
        }).on("fileuploaded", function (event, data, previewId, index) {
            console.log(data);
            var ret = data.response;
            if (ret.status != 0) {
                return commonUtil.toast(ret.msg);
            }
            G_ADD_IMAGE_SELECTED = ret.data.url;

            $('#app_template_category_detail_list_panel').find('img:eq(1)').attr('src', G_ADD_IMAGE_SELECTED)
        });

    }

    exports.init = init;
});